package repository

import (
	"fmt"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
)

type hostRepository struct{}

func (r hostRepository) FindByHostnameAndMac(hostname, mac string) (m model.AppHost, err error) {
	err = db.GetDB().Where("host_name =? and mac = ? limit 1", hostname, mac).Find(&m).Error
	return
}

func (r hostRepository) Insert(u *model.AppHost) error {
	return db.GetDB().Create(u).Error
}

func (r hostRepository) FindById(id int64) (u model.AppHost, err error) {
	err = db.GetDB().Where("host_id=?", id).Find(&u).Error
	return
}

func (r hostRepository) FindByIpAndPort(ip string, port int) (u model.AppHost, err error) {
	err = db.GetDB().Where("ip = ? and communication_port = ? ", ip, port).Find(&u).Error
	return
}

func (r hostRepository) UpdateById(u *model.AppHost) (err error) {
	if _, err = r.FindById(u.HostId); err != nil {
		return fmt.Errorf("cluster not exist")
	}
	return db.GetDB().Save(&u).Error
}
func (r hostRepository) FindAll() (results []model.AppHost, total int64, err error) {
	err = db.GetDB().Model(&model.AppHost{}).
		Find(&results).Count(&total).Error
	return
}

func (r hostRepository) DeleteMapHostForAPP(hostId int64) (err error) {
	err = db.GetDB().Exec("delete from sys_map_host_app where host_id = ? ", hostId).Error
	return
}

func (r hostRepository) UpdateClusterId(hostIds []int64, clusterId int64) error {
	if len(hostIds) == 0 {
		return nil
	}
	return db.GetDB().Model(&model.AppHost{}).Where("host_id in ? ", hostIds).Update("cluster_id", clusterId).Error
}

func (r hostRepository) FindWithClusterId(clusterId int64) (li []model.AppHost, err error) {
	err = db.GetDB().Where("cluster_id = ? ", clusterId).Find(&li).Error
	return
}

// ReturnHost 归还主机到默认集群中
func (r hostRepository) ReturnHost(clusterId int64) error {
	return db.GetDB().Model(&model.AppHost{}).Where("cluster_id = ? ", clusterId).Update("cluster_id", model.DefaultClusterId).Error
}

func (r hostRepository) FindPrivateHost(userId, clusterId int64) (m model.AppHost, err error) {
	err = db.GetDB().Model(&model.AppHost{}).Where("bind_user_id = ? and cluster_id = ? ", userId, clusterId).Find(&m).Error
	if err != nil {
		return
	}
	return
}

// SelectZeroSessionHost 查询活跃会话数为0且没有被私人绑定也没有被锁定的主机，也就是完全空闲的主机
func (r hostRepository) SelectZeroSessionHost(clusterId int64) (li []model.AppHost, err error) {
	err = db.GetDB().Raw("SELECT * FROM va_host WHERE "+
		" cluster_id =? AND bind_user_id =0 AND locked_user_id =0 "+
		" AND host_id NOT IN "+
		" ( SELECT host_id FROM 'va_host_session' WHERE cluster_id =1 AND hold_status = ? )",
		clusterId, model.VaSessionHoldForHolding).Find(&li).Error
	return
}
